import { ref, getCurrentInstance } from "vue";
import type { labelData } from "../utils/interface";
import { getTimeYMDHMS } from "../utils/time";
import { useUserStore } from "../stores/user";
import { useCode } from "../hooks/codeHook";
import { addLabelApi, getLabelApi } from "../api/label_api";

export function useLabel() {
  const proxy: any = getCurrentInstance()?.proxy;
  const { tackleCode } = useCode();
  const userStore = useUserStore();
  //取消
  function cancel() {
    inputValue.value = "";
  }
  //新建分组内容
  const inputValue = ref<number | string>();

  //标签数据集
  const label = ref<labelData[]>([]);
  //获取标签
  const rawLabel = () => {
    let request = {
      token: userStore.token,
    };
    getLabelApi(request).then((res: any) => {
      if (tackleCode(res.data.code)) {
        label.value = res.data.data;
      }
    });
  };

  //新建标签
  function confirm() {
    if (inputValue.value) {
      let request = {
        token: userStore.token,
        value: {
          label_name: inputValue.value,
          created_at: getTimeYMDHMS(new Date()),
        },
      };
      addLabelApi(request).then((res: any) => {
        if (tackleCode(res.data.code)) {
          inputValue.value = "";

          proxy.$message({ type: "primary", message: "添加成功" });
          rawLabel();
        }
      });
    }
  }

  return {
    confirm,
    cancel,
    rawLabel,
    label,
    inputValue,
  };
}
